package netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import netty.model.MethodInvokeMeta;
import org.springframework.stereotype.Component;

/**
 * 发送消息 网络
 *
 * @author Administrator
 */
@Component("nettyClient")
public class NettyClient
{
	private Bootstrap bootstrap;

	private EventLoopGroup worker;

	private String host = "127.0.0.1";

	private int port = 9999;

	private int MAX_RETRY_TIMES = 10;

	public NettyClient()
	{
		bootstrap = new Bootstrap();
		worker = new NioEventLoopGroup();
		bootstrap.group(worker);
		bootstrap.channel(NioSocketChannel.class);
	}

	public Object remoteCall(final MethodInvokeMeta cmd, int retry)
	{
		try
		{
			CustomChannelInitializer handler = new CustomChannelInitializer(cmd);
			bootstrap.handler(handler);
			ChannelFuture future = bootstrap.connect(host, port).sync();
			future.channel().closeFuture().sync();
			Object response = handler.getResponse();
			return response;
		}
		catch (Exception e)
		{
			retry++;
			if (retry > MAX_RETRY_TIMES)
			{
				throw new RuntimeException("调用出错...");
			}
			else
			{
				try
				{
					Thread.sleep(100);
				}
				catch (InterruptedException e1)
				{
					e1.printStackTrace();
				}
				System.err.println("尝试 " + retry + " 次，后失败");
				return remoteCall(cmd, retry);
			}

		}
	}

	public void close()
	{
		System.out.println("关闭资源");
		worker.shutdownGracefully();
	}

}
